package com.wugh.fast.security.social.app.qq.connet;

import com.google.common.base.Splitter;
import com.wugh.fast.kernel.core.enums.FastExceptionEnum;
import com.wugh.fast.kernel.core.exception.FastBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明:
 *
 * @author wugh
 * @date 2018/9/13 18:25
 */
@Slf4j
public class QQOAuth2Template extends OAuth2Template {
    public static Splitter URL_AND_SPLITTER = Splitter.on("&");
    public static Splitter URL_EQUAL_SPLITTER = Splitter.on("=").limit(2);

    public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        String responseStr = getAccessToken(accessTokenUrl, parameters);
        Map<String, String> params = new HashMap<>();
        URL_AND_SPLITTER.split(responseStr).forEach(param -> {
            List<String> keyValue = URL_EQUAL_SPLITTER.splitToList(param);
            params.put(keyValue.get(0), keyValue.get(1));
        });
        String accessToken = params.get("access_token");
        Long expiresIn = Long.parseLong(params.get("expires_in"));
        String refreshToken = params.get("refresh_token");

        return new AccessGrant(accessToken, null, refreshToken, expiresIn);
    }

    private String getAccessToken(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        String responseStr = "";
        int time = 0;
        do {
            if (time != 0) {
                log.info("系统-用户中心-qq授权异常 第{}次：{}", time++, responseStr);
            }
            if (time > 10) {
                throw new FastBusinessException("多次尝试qq授权失败,请稍后重试", FastExceptionEnum.GLOBAL_BUSINESS_EXCEPTION);
            }
            responseStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
            time++;
        } while (responseStr.startsWith("callback("));
        //access_token=A8213EAE5D75384A1E32DFB593245862&expires_in=7776000&refresh_token=9533E563EDBB33D1BC709D750D042812
        log.debug("系统-用户中心-qq授权返回：{}", responseStr);
        return responseStr;
    }

    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate restTemplate = super.createRestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }

}
